package com.pai4j.zwiki.service;

import com.pai4j.zwiki.dto.UserVipInfo;
import com.pai4j.zwiki.enums.UserVipLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 用户VIP服务
 * 管理用户VIP等级和权益
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserVipService {

    private final RedisTemplate<String, Object> redisTemplate;

    private static final String VIP_INFO_KEY_PREFIX = "zwiki:vip:user:";
    private static final long VIP_INFO_EXPIRE_SECONDS = 3600; // 1小时缓存

    /**
     * 获取用户VIP信息
     * 
     * @param userId 用户ID
     * @return VIP信息
     */
    public UserVipInfo getUserVipInfo(Long userId) {
        if (userId == null) {
            return UserVipInfo.createNormal(null);
        }

        // 尝试从缓存获取
        String cacheKey = VIP_INFO_KEY_PREFIX + userId;
        UserVipInfo cachedInfo = (UserVipInfo) redisTemplate.opsForValue().get(cacheKey);
        
        if (cachedInfo != null) {
            return cachedInfo;
        }

        // TODO: 从数据库或远程服务查询用户VIP信息
        // 这里暂时返回模拟数据，实际应该查询用户表或VIP服务
        UserVipInfo vipInfo = mockGetUserVipInfo(userId);

        // 缓存VIP信息
        redisTemplate.opsForValue().set(cacheKey, vipInfo, VIP_INFO_EXPIRE_SECONDS, TimeUnit.SECONDS);

        return vipInfo;
    }

    /**
     * 判断用户是否为VIP
     */
    public boolean isVipUser(Long userId) {
        UserVipInfo vipInfo = getUserVipInfo(userId);
        return vipInfo.isValidVip();
    }

    /**
     * 获取用户队列优先级
     */
    public Integer getUserPriority(Long userId) {
        UserVipInfo vipInfo = getUserVipInfo(userId);
        return vipInfo.getPriority();
    }

    /**
     * 获取用户最大并发任务数
     */
    public Integer getUserMaxConcurrentTasks(Long userId) {
        UserVipInfo vipInfo = getUserVipInfo(userId);
        return vipInfo.getAvailableConcurrentTasks();
    }

    /**
     * 判断用户是否应该使用VIP通道
     */
    public boolean shouldUseVipChannel(Long userId) {
        UserVipInfo vipInfo = getUserVipInfo(userId);
        return vipInfo.getUseVipChannel() != null && vipInfo.getUseVipChannel();
    }

    /**
     * 模拟获取用户VIP信息
     * TODO: 实际应该从数据库或远程服务获取
     */
    private UserVipInfo mockGetUserVipInfo(Long userId) {
        // 这里可以根据userId判断，或者查询数据库
        // 示例：userId % 10 == 0 为VIP3，% 5 == 0 为VIP2，% 3 == 0 为VIP1
        UserVipLevel vipLevel;
        
        if (userId % 10 == 0) {
            vipLevel = UserVipLevel.VIP3;
        } else if (userId % 5 == 0) {
            vipLevel = UserVipLevel.VIP2;
        } else if (userId % 3 == 0) {
            vipLevel = UserVipLevel.VIP1;
        } else {
            vipLevel = UserVipLevel.NORMAL;
        }

        return UserVipInfo.builder()
                .userId(userId)
                .vipLevel(vipLevel)
                .expired(false)
                .expireTime(vipLevel.isVip() ? LocalDateTime.now().plusMonths(1) : null)
                .availableConcurrentTasks(vipLevel.getMaxConcurrentTasks())
                .priority(vipLevel.getPriority())
                .useVipChannel(vipLevel.getUseVipChannel())
                .build();
    }

    /**
     * 清除用户VIP缓存
     */
    public void clearUserVipCache(Long userId) {
        String cacheKey = VIP_INFO_KEY_PREFIX + userId;
        redisTemplate.delete(cacheKey);
        log.info("清除用户VIP缓存: userId={}", userId);
    }

    /**
     * 更新用户VIP等级（管理员操作）
     */
    public void updateUserVipLevel(Long userId, UserVipLevel vipLevel, LocalDateTime expireTime) {
        // TODO: 更新数据库
        
        // 清除缓存
        clearUserVipCache(userId);
        
        log.info("更新用户VIP等级: userId={}, level={}, expireTime={}", 
                userId, vipLevel.getName(), expireTime);
    }
}

